package com.apop.accompanyH5.auth;

import com.apop.accompany.enums.ErrorCodeConstantsAccompany;
import com.apop.common.model.Result;
import com.apop.hrss.jwt.model.UserAuth;
import com.apop.hrss.jwt.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@RestController
@RequestMapping("/pzH5/auth")
public class H5LoginController {

    @Autowired
    AuthorizationService authorizationService;

    //用一个hashmap存储H5端注册用户 仅供演示
    private static ConcurrentHashMap<String, UserAuth> h5MemberMap = new ConcurrentHashMap<>();

    static {

        // 默认创建一个H5用户
        {
            UserAuth user5 = new UserAuth("admin5","admin");
            //注册成功
            h5MemberMap.put("admin5",user5);
        }

    }

    @PostMapping("/h5login")
    public Result h5login(@RequestBody Map requestData){

        String username = (String)requestData.get("username");
        String password = (String)requestData.get("password");
        UserAuth user = h5MemberMap.get(username);
        if(user != null && password != null && password.equals(user.getPassword())){

            // 登录成功

            // 创建token
            String token = authorizationService.createToken(user);

            // 更新用户最近登录时间
            user.setLastLoginTime(new Date().toString());
            h5MemberMap.put(username, user);

            return Result.success(token);
        }
        return Result.fail(ErrorCodeConstantsAccompany.AUTH_ERR_USER_NOT_FOUND);
    }

}
